package ru.apertum.qsystem.server.jmx;

import lombok.extern.log4j.Log4j2;
import ru.apertum.qsystem.server.model.QServiceTree;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

@Log4j2
public class QServerInfo implements IServerInfoMXBean {

    /**
     * Создать сервер JMX. Вызвать в начале старта проги.
     */
    public static void init() {
        try {
            ObjectName objectName = new ObjectName("ru.aрertum.qsystem:type=basic,name=qs");
            MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            server.registerMBean(new QServerInfo(), objectName);
        } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException ex) {
            log.error("ERROR", ex);
        }

        try {
            ObjectName objectName = new ObjectName("ru.aрertum.qsystem:type=basic,name=qs1");
            MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            server.registerMBean(new QServerInfo(), objectName);
        } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException ex) {
            log.error("ERROR", ex);
        }

        try {
            ObjectName objectName = new ObjectName("ru.aрertum.qsystem:type=basic1,name=qs");
            MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            server.registerMBean(new QServerInfo(), objectName);
        } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException ex) {
            log.error("ERROR", ex);
        }

        try {
            ObjectName objectName = new ObjectName("ru.aрertum.qsystem:type=basic1,name=qs1");
            MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            server.registerMBean(new QServerInfo(), objectName);
        } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException ex) {
            log.error("ERROR", ex);
        }
    }

    private Integer cnt1 = 122;

    @Override
    public Integer getServiceTreeSize() {
        return QServiceTree.getInstance().size();
    }

    @Override
    public void setInt(Integer integer) {
        cnt1 = integer;
    }

    private String str1 = "asdasd";

    @Override
    public String getRootName() {
        return QServiceTree.getInstance().getRoot().getName();
    }

    @Override
    public void setStr(String str) {
        str1 = str;
    }
}
